package com.shiliao.app.update;

import android.animation.Animator;
import android.animation.AnimatorInflater;
import android.app.Activity;
import android.content.Context;
import android.support.v4.widget.ContentLoadingProgressBar;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;

import com.shiliao.app.R;
import com.shiliao.app.ShiliaoApplication;
import com.shiliao.app.update.dowload.FileDownloadListener;
import com.shiliao.app.update.dowload.SilentConfig;
import com.shiliao.app.update.dowload.SilentDownloadService;
import com.shiliao.app.utils.KeyUtils;
import com.yimei.framework.ui.dilaog.AnimationType;
import com.yimei.framework.ui.dilaog.YimeiBaseDialog;
import com.yimei.framework.ui.widght.YimeiText;
import com.yimei.framework.util.LogUtil;
import com.yimei.framework.util.MyTimeUtils;
import com.yimei.framework.util.PreferenceHelper;
import com.yimei.framework.util.SystemUtils;

import java.io.File;
import java.util.Date;

public class YimeiFileDownloadDialog extends YimeiBaseDialog implements FileDownloadListener, View.OnClickListener {

    private static final String KEY_SHOW_UPDATE_DIALOG = "show_update_dialog";

    private ContentLoadingProgressBar mProgressBar;
    private RelativeLayout progressView;//下载更新的view
    private RelativeLayout updateInfoView; //更新提示的view
    private Button leftCancelButton;//左边取消按钮
    private Button rightSureButton;//右边确定按钮
    private YimeiText updateInfo;
    private UpdateEntity updateEntity;
    private RelativeLayout viewInstall;
    private Button installButton;//安装
    private Activity mActivity;

    public YimeiFileDownloadDialog(Activity activity, UpdateEntity updateEntity) {
        super(activity);
        try {
            if (activity != null && getLayoutInflater() != null) {
                mActivity = activity;
                setDialogCancelable(false);
                this.updateEntity = updateEntity;
                mDialog.setCanceledOnTouchOutside(false);
                mContainerView = getLayoutInflater().inflate(
                        R.layout.layout_download_dialog, null);
                // mWindow.setBackgroundDrawableResource(R.drawable.widget_dialog_background);
                mWindow.setGravity(Gravity.CENTER);
                // 填充progressbar
                mProgressBar = (ContentLoadingProgressBar) mContainerView.findViewById(R.id.download_seekbar);
                progressView = (RelativeLayout) mContainerView.findViewById(R.id.view_download_progress);
                progressView.setVisibility(View.GONE);
                updateInfoView = (RelativeLayout) mContainerView.findViewById(R.id.view_update_info);
                updateInfoView.setVisibility(View.VISIBLE);
                viewInstall = (RelativeLayout) mContainerView.findViewById(R.id.view_install);
                viewInstall.setVisibility(View.GONE);
                installButton = (Button) mContainerView.findViewById(R.id.button_install_app);
                installButton.setOnClickListener(this);
                leftCancelButton = (Button) mContainerView.findViewById(R.id.buton_left);
                leftCancelButton.setOnClickListener(this);
                rightSureButton = (Button) mContainerView.findViewById(R.id.button_right);
                rightSureButton.setOnClickListener(this);
                updateInfo = (YimeiText) mContainerView.findViewById(R.id.update_info);
                setInAnimation(AnimationType.DIALOG_FADE);
                updateInfoViewData();

            }
        } catch (Exception e) {
            LogUtil.e(e.getLocalizedMessage());
        }
    }

    private boolean fileIsExist() {
        if (updateEntity != null) {
            String[] names = updateEntity.url.split("\\/");
            String name = names[names.length - 1];
            File file = new File(SilentConfig.DOWNLOAD_PATH + name);
            return file.exists();

        }
        return false;
    }

    private void updateInfoViewData() {
        if (this.updateEntity != null) {
            updateInfo.setText(this.updateEntity.getUpdateMsg());
            if (fileIsExist()) {
                rightSureButton.setText("即刻安装");
            } else {
                rightSureButton.setText("立即下载");
            }
            if (updateEntity.forceUpdate == 1) {
                //强制更新不可跳过
                leftCancelButton.setVisibility(View.GONE);
            } else {
                leftCancelButton.setVisibility(View.VISIBLE);
                saveUpdateDialogTime(mActivity, System.currentTimeMillis() + "");
            }
        }
    }

    /**
     * 设置更新entity数据
     *
     * @param updateEntity
     */
    public void setUpdateEntity(UpdateEntity updateEntity) {
        this.updateEntity = updateEntity;
        updateInfoViewData();

    }

    /**
     * 更新下载进度
     *
     * @param fileSize
     * @param completeSize
     */
    @Override
    public void updateProgress(long fileSize, long completeSize) {
        // LogUtil.e("yjl", "filesize:" + fileSize + "====completeSize:" + completeSize);
        final float pro = (float) completeSize / (float) fileSize;
        if (mProgressBar != null && mActivity != null) {
            mActivity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    // LogUtil.e("yjl", "progress:" + pro);
                    mProgressBar.setProgress((int) (pro * 100));
                }
            });
        }

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.buton_left:
                dismiss();
                break;
            case R.id.button_right:
                if (fileIsExist()) {
                    String[] names = updateEntity.url.split("\\/");
                    String name = names[names.length - 1];
                    File file = new File(SilentConfig.DOWNLOAD_PATH + name);
                    SystemUtils.installApk(mActivity, file);
                } else {
                    startDownload();
                }
                break;
            case R.id.button_install_app:
                //下载完了必须安装
                if (updateEntity != null && fileIsExist()) {
                    String[] names = updateEntity.url.split("\\/");
                    String name = names[names.length - 1];
                    File file = new File(SilentConfig.DOWNLOAD_PATH + name);
                    SystemUtils.installApk(mActivity, file);
                }
                if (updateEntity != null
                        && updateEntity.forceUpdate != 0) {
                    setDialogCancelable(true);
                }
                break;
        }
    }


    private void startDownload() {
        showProgressView();
        UpateManager.startDowload(this.updateEntity, true);
    }

    /**
     * 展示下载进度页面
     */
    private void showProgressView() {
        viewInstall.setVisibility(View.GONE);
        updateInfoView.setVisibility(View.GONE);
        progressView.setVisibility(View.VISIBLE);
        Animator animation =
                AnimatorInflater.loadAnimator(mActivity, R.animator.anim_aphla_show);
        animation.setTarget(progressView);
        animation.start();
    }

    /**
     * 显示提示安装
     */
    private void showInstallView() {
        viewInstall.setVisibility(View.VISIBLE);
        installButton.setText("立刻安装");
        updateInfoView.setVisibility(View.GONE);
        progressView.setVisibility(View.GONE);
        Animator animation =
                AnimatorInflater.loadAnimator(mActivity, R.animator.anim_aphla_show);
        animation.setTarget(viewInstall);
        animation.start();
    }

    /**
     * 下载完成
     */
    @Override
    public void downloadFinish(long fileSize) {
        LogUtil.e("yjl", "下载完成:" + fileSize);
        if (updateEntity != null) {
            String[] names = updateEntity.url.split("\\/");
            String name = names[names.length - 1];
            File file = new File(SilentConfig.DOWNLOAD_PATH + name);
            if (file.exists() && file.length() == fileSize) {
                LogUtil.e("yjl", "app下载完成");
                showInstallView();
            }
        }
    }

    @Override
    public void show(boolean isAutoDismiss) {
        SilentDownloadService.addDownloadListener(this);
        super.show(isAutoDismiss);
    }

    @Override
    public void dismiss() {
        SilentDownloadService.removeDownloadListener(this);
        super.dismiss();
    }

    /**
     * 读取上次展示更新弹窗时间
     *
     * @param context
     * @return
     */
    public static String readUpdateDialogTime(Context context) {
        return PreferenceHelper.readString(context, KeyUtils.SETTING_FILE,
                KEY_SHOW_UPDATE_DIALOG, "0");
    }

    /**
     * 保存上次更新弹窗时间
     *
     * @param context
     * @param time
     */
    public static void saveUpdateDialogTime(Context context, String time) {
        PreferenceHelper.write(context, KeyUtils.SETTING_FILE,
                KEY_SHOW_UPDATE_DIALOG, time);
    }

    /**
     * 是否显示非强制更新的弹窗
     *
     * @return true 显示，false不显示
     */
    public static boolean isShowUpdateDialog() {
        String oldTime = readUpdateDialogTime(ShiliaoApplication.getInstance());
        Date oldDate = new Date(Long.valueOf(oldTime));
        long nowTime = System.currentTimeMillis();
        Date nowDate = new Date(nowTime);
        return !MyTimeUtils.isSameDay(oldDate, nowDate);
    }

}
